package com.wsx.ones.cloud.trans;

import com.gexin.fastjson.JSON;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 透传的实现，针对只给客户端传输数据，客户端自己决定怎么处理，后台进行操作
 * 和推送的主要区别是内容模板不同
 * Created by wangshuaixin on 17/6/1.
 */
public class TransData {

    private static String appId = "lShhx0b8AA8TecIaKvNkG7";
    private static String appKey = "CpBToh7j0t6TbE8Nstyd73";
    private static String masterSecret = "IFNCo6pLHK7c7Po3X8tYBA";
    //客户端的唯一编码key
    private static String CID = "0cf5a06122746fc0975564050d567b94";

    //加密https的体现，可以使用https来直接实现，如果采用http也可以
    private static String url = "https://sdk.open.api.igexin.com/apiex.htm";

    private static String host = "https://api.getui.com/apiex.htm";

    public static void main(String[] args) {

        //IGtPush push = new IGtPush(url, appKey, masterSecret);

        //加密的另一种提现方式，没有特别要求，可以不指定host
        IGtPush push = new IGtPush(appKey, masterSecret, true);

        TransmissionTemplate template = getTransmissionTemplate();

        SingleMessage message = new SingleMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);
        Target target = new Target();
        target.setAppId(appId);
        target.setClientId(CID);
        //target.setAlias(Alias);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToSingle(message, target);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }
    }

    /**
     * 获得透传模板内容
     * @return
     */
    private static TransmissionTemplate getTransmissionTemplate() {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);

        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(getContent());

        // 设置定时展示时间
        // template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00");
        return template;
    }

    private static String getContent() {
        Map<String, String> map = new HashMap<>();
        map.put("status", "200");
        map.put("data", "hello");
        map.put("msg", "中文字段内容展示");
        map.put("source", "app");

        return JSON.toJSONString(map);
    }
}
